<template>
  <el-form :model="Profile" :rules="rules" ref="Profile">
    <el-form-item label="请选择一个用户名" prop="username" required>
      <el-input v-model="Profile.username"></el-input>
    </el-form-item>
    <el-form-item>
      <el-row type="flex" justify="space-around">
        <el-button plain @click="submitForm('Profile')">提交</el-button>
      </el-row>
    </el-form-item>
  </el-form>
</template>

<script>
import { AuthGetCheckUsername, AuthPostUsername } from '@/utils/request'
import { setAuth } from '@/utils/checkAuth'

export default {
  name: 'cl-username-bound',
  data () {
    const check = (rule, value, callback) => {
      AuthGetCheckUsername({
        username: value
      }).then(rsp => {
        const available = rsp.data
        if (available) {
          callback()
        } else {
          callback(new Error('该用户名已被占用，请更换用户名'))
        }
      })
    }
    return {
      Profile: {
        username: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: check, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          AuthPostUsername(this.Profile).then(rsp => {
            console.log(rsp)
            const { available } = rsp.data
            if (available) {
              const { id, name, admin } = rsp.data
              setAuth(id, name, admin)
              this.$router.push({
                name: 'MarketList'
              })
            }
          })
          console.info(this.Profile)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-demo {
  display: block;
}
</style>
